/*
 * @Author: wangrongrong
 * @Date: 2023-08-28 15:14:27
 * @LastEditTime: 2023-09-11 11:01:44
 * @LastEditors: wangrongrong
 * @Description: 
 * @FilePath: /unattended-backstage-fe/src/service/server.js
 * 
 */
/**
 * 公用接口封装,所有接口请求必须经过这里
 */
import axios from 'axios'
import qs from 'qs'
import { useRouter } from "vue-router"
import { ElMessage, ElMessageBox } from "element-plus";
import { setAPI } from '@/utils/env';
import Toast from '@/common/toast';

const router = useRouter()

axios.defaults.withCredentials = true;

export default function (opt) {
  let dataList = {
    method: opt.method || 'get',
    url: `${setAPI(opt.apiType)}${opt.url}`,
    timeout: opt.timeout || 10000,
    headers: {
      'Content-Type': opt.contentType || 'application/json;charset=UTF-8',
    },
    data: {},
  }

  if (opt.dataType) {
    dataList.dataType = opt.dataType;
  }
  console.log('---------', dataList.url);
  const token = localStorage.getItem('login_token')
  if (token) {
    opt.data.token = token
  }
  if (dataList.method === 'post') {
    if (dataList.dataType === 'json') {
      dataList.data = JSON.stringify(opt.data);
    } else if (opt.dataType === 'multipart') {
      dataList.data = opt.data;
    } else {
      dataList.data = qs.stringify(opt.data);
    }
  } else if (dataList.method === 'get') {
    dataList.params = opt.data;
  }

  return new Promise((resolve, reject) => {
    axios(dataList).then(res => {
      resolve(res.data)
    }).catch(error => {
      console.log('server Err:', error);
      reject(error)
    })
  })
}

// 发送请求前处理数据
axios.interceptors.request.use(config => {
  return config;
}, error => {
  return Promise.reject(error);
});

// 返回响应请求后处理数据
axios.interceptors.response.use(res => {
  console.log(res)
  if (res.status == '200' && res.data && res.data.status === 0) {
    return res
  } else if (res.data && res.data.status === -2) {
    // 提示登录
    ElMessageBox.confirm('当前用户信息已经失效，请重新登录.', '登录失败', {
      distinguishCancelAndClose: true,
      confirmButtonText: '确定'
    }).then(() => {
      router.push({
        path: '/login',
        query: {
          riderect: encodeURIComponent(location.href)
        }
      })
    }).catch((action) => {

    });
  } else {
    ElMessage({
      showClose: true,
      message: res.data.message,
      type: "error",
    });
  }
  return res;
}, error => {
  let errorCode = error.response.status;
  Toast(error.response.statusText);
  return Promise.reject(error);
});
